import html2canvas from 'html2canvas';
/**
 * 获取指定dom节点生成的图片 - 截屏
 * @export
 * @class ScreenshotsUtil
 */

// 获取截图
function screenshots(options={}) {
  let { canvasBox, canvasBoxOffsetLeft, canvasBoxOffsetTop, canvasBoxOffsetHeight } = options
  // 大概估算出，图片最大面积为maxPixels，超出只能舍弃一些分辨率，判断请转到scale配置
  const maxPixels = 880 * 3270 * 0.85;

  // console.log('getHtmlImage 配置项=》》》》》》',options)
  return new Promise ((resolve, reject) => {
    if (!canvasBox) {
      reject(null)
    }
    
    let domWidth = canvasBox.offsetWidth
    let domHeight = canvasBoxOffsetHeight || canvasBox.offsetHeight
    console.log(domWidth, domHeight)

    //定时为了解决页面太长，未加载出来时就截图，导致图片不完整
    setTimeout(() => {
      html2canvas(canvasBox, {
        // allowTaint: true, //是否允许跨域，会对canvas造成污染，导致无法使用canvas.toDataURL 方法
        useCORS: true, //是否允许跨域
        // proxy: 'https://test.test.com',
        backgroundColor: '#fff', //解决生成图片有白色背景方法，设置为null
        width: domWidth,
        height: domHeight,
        x: canvasBoxOffsetLeft || canvasBox.offsetLeft, 
        y: canvasBoxOffsetTop || canvasBox.offsetTop,
        // x: 397, 
        // y: 490,
        scale: maxPixels / (domWidth*domHeight) > 1 ? 1 : maxPixels / (domWidth*domHeight),
      }).then((canvas)=>{
        if(canvas){
          let dataUrl = canvas.toDataURL('image/png'); // image/png ， image/jpg
          // console.log('dataUrl=>>>>>>>>',dataUrl)
          // let newImg = document.createElement("img");
          // // //newImg.style = "display:none;";    //如果要导出，这儿可以隐藏，然后用canvas2image搞定
          // newImg.src = dataUrl;
          // document.body.appendChild(newImg);
  
          resolve(dataUrl)
					// reject(null)
        }else{
          reject(null)
        }
      });
    }, 500);
  })
}

module.exports = {
	screenshots:screenshots
}